﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Traceability.API.Applications.Command.TracebackCommand;
using Traceability.Domain;
using Traceability.Domain.DTO.Output;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.API.Applications.CommandHandler.TracebackCommandHandler
{
    public class TracebackQueryCommandHandler : IRequestHandler<TracebackQueryCommand, APIPaging<TracebackQueryDTO>>
    {
        private readonly IBaseRepository<Traceback_Information> _tracebackRepository;
        private readonly IBaseRepository<Aquaculture_Information> _aquacultureRepository;
        private readonly IBaseRepository<Slaughter_Information> _slaughterRepository;
        private readonly IBaseRepository<Deep_Processing> _deepRepository;
        private readonly IMapper _mapper;

        public TracebackQueryCommandHandler(IBaseRepository<Traceback_Information> tracebackRepository, IBaseRepository<Aquaculture_Information> aquacultureRepository, IBaseRepository<Slaughter_Information> slaughterRepository, IBaseRepository<Deep_Processing> deepRepository, IMapper mapper)
        {
            _tracebackRepository = tracebackRepository;
            _aquacultureRepository = aquacultureRepository;
            _slaughterRepository = slaughterRepository;
            _deepRepository = deepRepository;
            _mapper = mapper;
        }
        public Task<APIPaging<TracebackQueryDTO>> Handle(TracebackQueryCommand request, CancellationToken cancellationToken)
        {
            // 使用JOIN而不是Include来关联表
            var query = from t in _tracebackRepository.GetAll().AsNoTracking().Where(s => !s.IsDeltede)
                        join a in _aquacultureRepository.GetAll().AsNoTracking() on t.Batch equals a.Batch into aquaGroup
                        from aqua in aquaGroup.DefaultIfEmpty()
                        join s in _slaughterRepository.GetAll().AsNoTracking() on t.Batch equals s.Batch into slaughterGroup
                        from slaughter in slaughterGroup.DefaultIfEmpty()
                        join d in _deepRepository.GetAll().AsNoTracking() on t.Batch equals d.Batch into deepGroup
                        from deep in deepGroup.DefaultIfEmpty()
                        select new 
                        { 
                            Traceback = t,
                            Aquaculture = aqua,
                            Slaughter = slaughter,
                            Deep = deep
                        };

            // 添加查询条件
            if (request.CreateUserId.HasValue)
                query = query.Where(x => x.Traceback.CreateUserId == request.CreateUserId);
            if (request.CreateTime.HasValue)
            {
                var time = Convert.ToDateTime(request.CreateTime);
                query = query.Where(x => x.Traceback.CreateTime>= request.CreateTime&& x.Traceback.CreateTime<time.AddSeconds(1));
            }
                
            if (request.UpDataUserId.HasValue)
                query = query.Where(x => x.Traceback.UpDataUserId == request.UpDataUserId);
            if (request.UpDataTime.HasValue)
            {
                var time = Convert.ToDateTime(request.UpDataTime);
                query = query.Where(x => x.Traceback.UpDataTime >= request.UpDataTime && x.Traceback.UpDataTime < time.AddSeconds(1));
            }
            if (!string.IsNullOrEmpty(request.SName))
                query = query.Where(x => x.Traceback.SName != null && x.Traceback.SName.Contains(request.SName));
            if (!string.IsNullOrEmpty(request.Batch))
                query = query.Where(x => x.Traceback.Batch != null && x.Traceback.Batch.Contains(request.Batch));
            if (request.Expiration_date.HasValue)
                query = query.Where(x => x.Traceback.Expiration_date == request.Expiration_date);
            if (!string.IsNullOrEmpty(request.Production_License))
                query = query.Where(x => x.Traceback.Production_License != null && x.Traceback.Production_License.Contains(request.Production_License));
            if (!string.IsNullOrEmpty(request.Manufacturing_Enterprises))
                query = query.Where(x => x.Traceback.Manufacturing_Enterprises != null && x.Traceback.Manufacturing_Enterprises.Contains(request.Manufacturing_Enterprises));

            // 获取总数
            int count = query.Count();
            
            // 排序和分页
            var pagedItems = query.OrderByDescending(x => x.Traceback.Id)
                .Skip((request.PageIndex - 1) * request.PageSize)
                .Take(request.PageSize)
                .ToList();

            // 处理结果，计算信息完善度
            var resultList = new List<Traceback_Information>();
            foreach (var item in pagedItems)
            {
                var traceback = item.Traceback;

            
                if (item.Aquaculture != null) traceback.nformation_Completeness+=30;
                if (item.Slaughter != null) traceback.nformation_Completeness += 30;
                if (item.Deep != null) traceback.nformation_Completeness += 30;
                
                
                resultList.Add(traceback);
            }

            var model = _mapper.Map<List<TracebackQueryDTO>>(resultList);

            APIPaging<TracebackQueryDTO> aPIPaging = new APIPaging<TracebackQueryDTO>()
            {
                Count = count,
                Code = EnumCode.Ok,
                Msg = "显示成功",
                PageData = model
            };

            return Task.FromResult(aPIPaging);
        }
    }
}
